package com.ganzalang.gmall.learning.netty.nio;

import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;


/**
 * @description: 用一个缓冲区完成文件的读写
 * @author: Ganzalang
 * @Date 2021/7/12 21:47
 */
@Slf4j
public class NIOFileChannel03 {

    public static void main(String[] args) throws IOException {

        // 从文件读取数据到缓冲区，要获取输入流以及对应的FileChannel
        FileInputStream fileInputStream = new FileInputStream("D:\\IDEAProject\\gmall-learning\\gmall-learning-netty\\1.txt");
        FileChannel fileChannel01 = fileInputStream.getChannel();

        // 将缓冲区的数据写入到文件
        FileOutputStream fileOutputStream = new FileOutputStream("D:\\IDEAProject\\gmall-learning\\gmall-learning-netty\\2.txt");
        FileChannel fileChannel02 = fileOutputStream.getChannel();

        // 创建缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(512);

        while (true) {

            // 清空buffer，实质是重置标志位
            buffer.clear();
            int read = fileChannel01.read(buffer);
            log.info("read={}", read);
            // -1表示结束
            if (read == -1) {
                break;
            }
            // 重置标志位，将buffer中的数据写入到2.txt
            buffer.flip();
            fileChannel02.write(buffer);
        }

        fileInputStream.close();
        fileOutputStream.close();
    }
}
